package city.spring.modules.system.service.impl;

import city.spring.modules.system.entity.PermissionCategoryEntity;
import city.spring.modules.system.entity.PermissionEntity;
import city.spring.modules.system.repository.PermissionCategoryRepository;
import city.spring.modules.system.service.PermissionCategoryService;
import city.spring.modules.system.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Service：权限信息类别表
 *
 * @author 侯坤林
 * @date 2020-06-15 09:33:11
 */
@CacheConfig(cacheNames = {PermissionCategoryServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class PermissionCategoryServiceImpl extends ServiceImpl<PermissionCategoryRepository, PermissionCategoryEntity> implements PermissionCategoryService {
    private final PermissionService permissionService;

    public PermissionCategoryServiceImpl(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    public void savePermissionCategory(PermissionCategoryEntity entity) {
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updatePermissionCategory(PermissionCategoryEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deletePermissionCategory(String primaryKey) {
        removeById(primaryKey);
        List<String> permissionIds = permissionService.lambdaQuery()
                .eq(PermissionEntity::getCategoryId, primaryKey)
                .list().stream().map(PermissionEntity::getId).collect(Collectors.toList());
        permissionService.deletePermission(permissionIds);
    }

    @Override
    public void deletePermissionCategory(List<String> primaryKeys) {
        removeByIds(primaryKeys);
        List<String> permissionIds = permissionService.lambdaQuery()
                .in(PermissionEntity::getCategoryId, primaryKeys)
                .list().stream().map(PermissionEntity::getId).collect(Collectors.toList());
        permissionService.deletePermission(permissionIds);
    }
}